/**
 * Created by Ysssssss on 21/3/2.
 */
import React, { PureComponent } from 'react'
import {Button, Input, Tabs, Select, Modal} from "antd";
import {connect} from "react-redux";
import {
    getShelfGroupList,
    getShelfProductList,
    bulkAddShelfProduct,
    bulkEditShelfProductStatus,
    bulkDeleteShelfProduct,
    bulkDeleteProductFromShelfGroup,
    deleteShelfGroup,
    sortShelfGroup,
    checkMenuInfo, bulkEditShelfProductPrice
} from "@sagas/shoppingMall/shoppingMallProduct";
import SearchInput from "@common/presentational/SearchInput";
import {getHistoryMatchParams, getQuery, handleQueryEqual, setQuery} from "@utils/setUrlQuery";
import {withRouter} from "react-router-dom";
import CustomizeTableProvide, {CustomizeTable, CustomizeTablePagination} from "@common/presentational/CustomizeTable";
import {CreateShelfGroupModal, EditShelfGroupModal} from "@components/shoppingMall/modal/ShelfGroupInfoModal";
import {
    MultiSelectShoppingMallImportProductModal
} from "@common/presentational/MultiSelectModal";
import {priceRangePreview} from "@utils/priceConversion";
import getCdnUrl from "@utils/getCdnUrl";
import {ShelfGroupSelectModal} from "@components/shoppingMall/modal/ShelfGroupSelectModal";
import DropdownMenu from "@common/presentational/DropdownMenu";
import {BulkEditProductPriceModal, SingleEditProductPriceModal} from "@common/presentational/EditProductPriceModal";
import {DndSortModal} from "@common/presentational/DndSortModal";
import BilinIcon from "@common/presentational/BilinIcon";

@connect(({shoppingMallProduct}) => ({
    shelfGroupList: shoppingMallProduct.shelfGroupList,
    shelfProductListPagination: shoppingMallProduct.shelfProductListPagination,
    shelfMenuInfo: shoppingMallProduct.shelfMenuInfo,
}), {
    getShelfGroupList,
    getShelfProductList,
    bulkAddShelfProduct,
    bulkEditShelfProductStatus,
    bulkDeleteShelfProduct,
    bulkDeleteProductFromShelfGroup,
    deleteShelfGroup,
    sortShelfGroup,
    checkMenuInfo,
    bulkEditShelfProductPrice
})
@withRouter
class ShoppingMallProductPage extends PureComponent {
    constructor(props) {
        super(props);

        const { groupId = '', query = '', status = '', groupStatus = ''} = getQuery(props.history)
        this.state = {
            groupId,
            query,
            status,
            groupStatus,
            selectedRows: []
        }

        this.tableRef = React.createRef()
        this.CreateShelfGroupModalRef = React.createRef()
        this.editShelfGroupModalRef = React.createRef()
        this.multiSelectProductModalRef = React.createRef()
        this.multiSelectProductFromMenuModalRef = React.createRef()
        this.shelfGroupSelectModalRef = React.createRef()
        this.bulkEditProductPriceModalRef =React.createRef()
        this.singleEditProductPriceModalRef =React.createRef()
        this.groupSortModalRef =React.createRef()

        this.paginationInfo = {}

        this.columns = [{
            key: 'custom_name',
            dataIndex: 'custom_name',
            title: '商品',
            render: (text, record) => (
                <div className="flex-vertical-center">
                    <img className="mgr-8" src={getCdnUrl(record.title_pic)} alt="" width={32} height={32}/>
                    <span>{ text || record.name }</span>
                </div>
            )
        }, {
            key: 'price_range',
            dataIndex: 'price_range',
            title: '价格',
            render: text => priceRangePreview(text)
        }, {
            key: 'prod_group_names',
            dataIndex: 'prod_group_names',
            title: '分组',
            render: text => text.length ? text.join(', ') : '未分组'
        }, {
            key: 'status',
            dataIndex: 'status',
            title: '状态',
            render: text => text ? '上架中' : '已下架'
        }, {
            key: 'id',
            dataIndex: 'id',
            title: '操作',
            render: (text, record) => (
                <div className="flex-vertical-center">
                    <div className="mgr-8 ft-hover"
                         onClick={this.goEditPage.bind(this, record.id)}
                    >编辑</div>
                    <div className="mgr-8 ft-hover"
                         onClick={this.handleProductStatusChange.bind(this, { id :record.id, status: !record.status })}
                    >{ record.status ? '下架' : '上架' }</div>
                    <DropdownMenu
                        dropdownList={[{
                            key: 'editPrice',
                            name: '修改价格',
                        }, {
                        //     key: 'setGroup',
                        //     name: '设置分组',
                        // }, {
                            key: 'delete',
                            name: '删除'
                        }]}
                        onClick={this.handleProductOperation.bind(this, record)}
                    >
                        <div className="ft-hover">更多</div>
                    </DropdownMenu>
                </div>
            )
        }]
    }

    componentDidMount () {
        this.getShelfGroupList()
        this.props.checkMenuInfo()
    }

    getShelfGroupList () {
        this.props.getShelfGroupList()
    }

    handleValueChange (key, value) {
        if (key === 'groupId') {
            this.setState({
                groupId: value ? parseInt(value) : '',
                groupStatus: '',
            }, this.initTable)
            return;
        }
        this.setState({
            [key]: value,
        }, this.initTable)
    }


    handleSelectRowsChange (rows) {
        this.setState({
            selectedRows: rows
        })
    }

    handleImportProduct (type) {
        type === 'menu' ?
            this.multiSelectProductFromMenuModalRef.current?.show() :
            this.multiSelectProductModalRef.current?.show()
    }

    productPriceChangeBulkAction (prods, callback) {
        this.props.bulkEditShelfProductPrice({
            prods
        }, () => {
            this.getTableInfo()
            callback && callback()
        })
    }

    productPriceChangeAction ({ id, skus }, callback) {
        this.props.bulkEditShelfProductPrice({
            prods: [{
                id,
                skus: skus.map(sku => ({
                    ...sku,
                    custom_price: sku.price
                }))
            }]
        }, () => {
            this.getTableInfo()
            callback && callback()
        })
    }

    handleProductChange (fromMenu, productList) {
        this.props.bulkAddShelfProduct({
            ids: productList.map(prod => prod.id),
            status: false,
            fromMenu
        }, () => {
            this.getTableInfo()
        })
    }

    goEditPage (id) {
        this.props.history.push(`/shopping-mall/product/${id}/edit`)
    }

    handleProductStatusChange ({ id, ids, status }) {
        this.props.bulkEditShelfProductStatus({
            ids: ids || [ id ],
            status
        }, () => {
            this.getTableInfo()
        })
    }

    handleProductGroupsChange ({ id, ids }) {
        this.shelfGroupSelectModalRef.current?.show({
            id, ids
        })
    }

    handleProductDelete ({ ids }) {
        this.props.bulkDeleteShelfProduct({
            ids
        }, () => {
            this.initTable()
        })
    }

    handleProductRemoveGroup ({ ids, groupId }) {
        this.props.bulkDeleteProductFromShelfGroup({
            ids,
            groupId
        }, () => {
            this.initTable()
        })
    }

    handleProductOperation (record, type) {
        const { selectedRows, groupId }= this.state
        switch (type) {
            case 'bulkEditPrice':
                this.bulkEditProductPriceModalRef.current?.show({
                    productList: selectedRows
                })
                break;
            case 'removeGroup':
                if (groupId) {
                    Modal.confirm({
                        title: '确认移出该分组？',
                        icon: null,
                        onOk: this.handleProductRemoveGroup.bind(this, {ids: selectedRows.map(row => row.id), groupId})
                    })
                }
                break;
            case 'bulkDelete':
                Modal.confirm({
                    title: '确认从货架上删除选中商品？',
                    icon: null,
                    onOk: this.handleProductDelete.bind(this, {ids: selectedRows.map(row => row.id)})
                })
                break;
            case 'editPrice':
                this.singleEditProductPriceModalRef.current?.show({
                    productInfo: record
                })
                break;
            case 'setGroup':
                this.handleProductGroupsChange({ id: record.id })
                break;
            case 'delete':
                Modal.confirm({
                    title: '确认从货架上删除选中商品？',
                    icon: null,
                    onOk: this.handleProductDelete.bind(this, {ids: [record.id]})
                })
                break;
            default:
                break;
        }
    }

    handleCreateShelfGroup () {
        this.CreateShelfGroupModalRef.current?.show()
    }

    handleDeleteSelfGroup (id) {
        const { groupId } = this.state
        this.props.deleteShelfGroup({
            id
        }, () => {
            if (groupId === id) {
                this.handleValueChange('groupId', '')
            }
            this.getShelfGroupList()
        })
    }

    handleGroupOperation (group, type) {
        switch (type) {
            case 'edit':
                this.editShelfGroupModalRef.current?.show(group)
                break;
            case 'delete':
                Modal.confirm({
                    title: '确认删除选中分组？',
                    icon: null,
                    onOk: this.handleDeleteSelfGroup.bind(this, group.id)
                })
                break
            default:
                break;
        }
    }

    handleSortGroup () {
        const { shelfGroupList } = this.props
        this.groupSortModalRef.current?.show({
            sortList: shelfGroupList
        })
    }

    sortGroupCallback (sortList, callback) {
        this.props.sortShelfGroup({
            ids: sortList.map(item => item.id)
        }, () => {
            callback && callback()
            this.getShelfGroupList()
        })
    }

    initTable () {
        this.tableRef.current?.initPage()
    }

    getTableInfo ({ current, pageSize } = this.paginationInfo) {
        this.paginationInfo = { current, pageSize }
        const { groupId, query, status, groupStatus, } = this.state
        this.props.getShelfProductList({
            groupId,
            query,
            status,
            groupStatus,
            pageNo: current,
            pageSize
        })
        this.setUrlQuery()
    }

    setUrlQuery () {
        const { current, pageSize } = this.paginationInfo
        const { history } = this.props
        const { groupId, query, status, groupStatus, } = this.state
        let params = {
            groupId,
            query,
            status,
            groupStatus,
            pageNo: current,
            pageSize,
        }
        handleQueryEqual(params, history) || setQuery(params, history)
    }

    render () {
        const { shelfProductListPagination, shelfGroupList, shelfMenuInfo } = this.props
        const { groupId, query, status, groupStatus, selectedRows } = this.state

        return (
            <div className="shopping-mall-page shopping-mall-product-page table-scroll-container">
                <div className="flex-row-between mgb-16">
                    { selectedRows.length ? (
                        <div className="flex-vertical-center">
                            <Button type="primary" ghost className="button-middle mgr-16" onClick={this.handleProductStatusChange.bind(this, {ids: selectedRows.map(row => row.id), status: true})}>上架</Button>
                            <Button type="primary" ghost className="button-middle mgr-16" onClick={this.handleProductStatusChange.bind(this, {ids: selectedRows.map(row => row.id), status: false})}>下架</Button>
                            <Button type="primary" ghost className="button-middle mgr-16" onClick={this.handleProductGroupsChange.bind(this, {ids: selectedRows.map(row => row.id) })}>添加分组</Button>
                            <DropdownMenu
                                dropdownList={[{
                                    key: 'bulkEditPrice',
                                    name: '修改价格',
                                }, ...(groupId ? [{
                                    key: 'removeGroup',
                                    name: '移出分组',
                                }] : []), {
                                    key: 'bulkDelete',
                                    name: '删除'
                                }]}
                                onClick={this.handleProductOperation.bind(this, {})}
                            >
                                <Button className="button-middle mgr-16">更多</Button>
                            </DropdownMenu>
                        </div>
                    ) : (
                        shelfMenuInfo?.has_menu ? (
                            <DropdownMenu
                                dropdownList={[{
                                    key: 'menu',
                                    name: '从品牌供货组选择',
                                }, {
                                    key: 'product',
                                    name: '从商品库选择'
                                }]}
                                onClick={this.handleImportProduct.bind(this)}
                            >
                                <Button type="primary" className="button-middle mgr-16">上架商品</Button>
                            </DropdownMenu>
                        ) : (
                            <Button type="primary" className="button-middle mgr-16" onClick={this.handleImportProduct.bind(this, 'product')}>上架商品</Button>
                        )
                    ) }
                    <SearchInput style={{ width: '240px' }}
                                 onChange={this.handleValueChange.bind(this, 'query')}
                                 initValue={query}
                                 value={query}
                                 placeholder="商品名称"/>
                </div>
                <Tabs
                    activeKey={`${groupId}`}
                    onChange={this.handleValueChange.bind(this, 'groupId')}
                    tabBarExtraContent={{
                        right: (
                            <>
                                <Button onClick={this.handleCreateShelfGroup.bind(this)}>新建分组</Button>
                                <Button className="mgl-24" onClick={this.handleSortGroup.bind(this)} disabled={shelfGroupList.length < 2}>分组排序</Button>
                            </>
                        )
                    }}
                >
                    <Tabs.TabPane
                        tab={(
                            <div className="group-tab">全部</div>
                        )}
                        key="0"
                    />
                    { shelfGroupList.map(group => (
                        <Tabs.TabPane
                            tab={(
                                <div className="group-tab">
                                    <span>{ group.name }</span>
                                    <DropdownMenu
                                        dropdownList={[{
                                            key: 'edit',
                                            name: '编辑',
                                        }, {
                                            key: 'delete',
                                            name: '删除'
                                        }]}
                                        onClick={this.handleGroupOperation.bind(this, group)}
                                        trigger={['click']}
                                    >
                                        <BilinIcon type="more-dropdown" className="hidden-visible group-operation" onClick={e => {e.stopPropagation()}}/>
                                    </DropdownMenu>
                                </div>
                            )}
                            key={`${group.id}`} />
                    )) }
                </Tabs>
                <div className="table-params page-params flex-vertical-center">
                    <Select className="mgr-16"
                            style={{width: '140px'}}
                            onChange={this.handleValueChange.bind(this, 'status')}
                            value={status}
                    >
                        <Select.Option key="all" value="">全部</Select.Option>
                        <Select.Option key="status_1" value={1}>上架中</Select.Option>
                        <Select.Option key="status_2" value={2}>已下架</Select.Option>
                    </Select>
                    { groupId ? null : (
                        <Select className="mgr-16"
                                style={{width: '140px'}}
                                onChange={this.handleValueChange.bind(this, 'groupStatus')}
                                value={groupStatus}
                        >
                            <Select.Option key="all" value="">全部</Select.Option>
                            <Select.Option key="groupStatus_1" value={1}>已分组</Select.Option>
                            <Select.Option key="groupStatus_2" value={2}>未分组</Select.Option>
                        </Select>
                    ) }
                </div>
                <CustomizeTableProvide ref={this.tableRef} tableKey="shoppingMallProductList" onChange={this.getTableInfo.bind(this)}>
                    <div className="table-list">
                        <CustomizeTable
                            columns={this.columns}
                            dataSource={shelfProductListPagination.prods || []}
                            pagination
                            selectionInfo={{
                                keyValue: 'id',
                                onChange: this.handleSelectRowsChange.bind(this),
                            }}
                        />
                    </div>
                    <div className="table-pagination">
                        <CustomizeTablePagination
                            total={shelfProductListPagination.total}
                        />
                    </div>
                </CustomizeTableProvide>
                <CreateShelfGroupModal ref={this.CreateShelfGroupModalRef} callback={this.getShelfGroupList.bind(this)}/>
                <EditShelfGroupModal ref={this.editShelfGroupModalRef} callback={this.getShelfGroupList.bind(this)}/>
                <MultiSelectShoppingMallImportProductModal
                    ref={this.multiSelectProductFromMenuModalRef}
                    title="上架供货组商品"
                    onChange={this.handleProductChange.bind(this, true)}
                    fromMenu={true}
                />
                <MultiSelectShoppingMallImportProductModal
                    ref={this.multiSelectProductModalRef}
                    title="上架商品"
                    onChange={this.handleProductChange.bind(this, false)}
                    fromMenu={false}
                />
                <ShelfGroupSelectModal
                    ref={this.shelfGroupSelectModalRef}
                    shelfGroupList={shelfGroupList}
                    callback={this.getTableInfo.bind(this)}
                />
                <BulkEditProductPriceModal
                    ref={this.bulkEditProductPriceModalRef}
                    priceEditAction={this.productPriceChangeBulkAction.bind(this)}
                />
                <SingleEditProductPriceModal
                    ref={this.singleEditProductPriceModalRef}
                    priceEditAction={this.productPriceChangeAction.bind(this)}
                />
                <DndSortModal
                    ref={this.groupSortModalRef}
                    title="分组排序"
                    type="shelfGroup"
                    callback={this.sortGroupCallback.bind(this)}
                />
            </div>
        )
    }
}

export default ShoppingMallProductPage